<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 书店
 */
class Shop extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'shop';

    /**
     * 书店筛选列表
     */
    public function wechatShopFiltrateList()
    {
        $data = $this->select('id', 'name')
            ->where('is_del', 1)
            ->whereIn('way', [1, 3])
            ->orderByDesc('id')
            ->get()
            ->toArray();
        return $data;
    }


    /**
     * 书店列表
     * @param way 类型 1开通荐购方式，线上线下等服务，2 只开通线下、3 只开通线上  多个逗号分隔
     * @param keywords string 搜索关键词(文章标题)
     * @param limit int 分页大小
     */
    public function lists($field = null, $way = null, $keywords = null, $shop_all_id = null, $limit = 10)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'province', 'city', 'district', 'address', 'tel', 'contacts', 'intro', 'lon', 'lat','way', 'create_time'];
        }
        $res = $this
            ->select($field)
            ->where('is_del', 1)
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', "%$keywords%");
                }
            })
            ->where(function ($query) use ($way) {
                if ($way) {
                    $way = !is_array($way) ? explode(',', $way) : $way;
                    $query->whereIn('way', $way);
                }
            })->whereIn('id', $shop_all_id)
            ->paginate($limit)
            ->toArray();
        return $res;
    }


    /**
     * 书店详情
     * @param $id 书店id
     * @param $shop_all_id int 管理员id
     */
    public function detail($id, $shop_all_id = null)
    {
        if (empty($field)) {
            $field = ['id', 'name', 'img', 'province', 'city', 'district', 'address', 'tel', 'contacts', 'intro', 'lon', 'lat', 'way', 'create_time'];
        }
        $res = $this
            ->select($field)
            ->where('id', $id)
            ->where('is_del', 1)
            ->whereIn('id', $shop_all_id)
            ->first();
        return $res;
    }
}
